<template>
	<view class="page-container">
		<scroll-view class="content-scroll" scroll-y>
			<!-- 球队基本信息 -->
			<view class="team-header">
				<image class="team-logo" :src="teamInfo.logo || '/static/avatars/default-avatar.jpg'" mode="aspectFill">
				</image>
				<view class="team-info">
					<view class="team-name">{{ teamInfo.name }}</view>
					<view class="team-meta">
						<text class="team-location">{{ teamInfo.address || '暂无地区' }}</text>
						<text class="team-create-time">创建于 {{ teamInfo.createTime || '--' }}</text>
					</view>
				</view>
			</view>

			<!-- 球队标签 -->
			<view class="team-tags" v-if="teamTags && teamTags.length">
				<text class="tag" v-for="(tag, index) in teamTags" :key="index">{{ tag.trim() }}</text>
			</view>

			<!-- 球队简介 -->
			<view class="team-description">
				<view class="section-title">球队简介</view>
				<view class="description-content">{{ teamInfo.description || '暂无简介' }}</view>
			</view>

			<!-- 球队成员 -->
			<view class="team-stats">
				<view class="stat-item">
					<text class="stat-value">{{ teamInfo.memberCount || 0 }}</text>
					<text class="stat-label">成员</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ recentActivities.length }}</text>
					<text class="stat-label">活动</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ teamInfo.momentCount || 0 }}</text>
					<text class="stat-label">动态</text>
				</view>
			</view>

			<!-- 最近一周活动 -->
			<view class="recent-activities">
				<view class="section-header" @tap="toggleActivities">
					<view class="header-left">
						<text class="section-title">最近一周活动</text>
						<text class="count">({{recentActivities.length}})</text>
					</view>
					<view class="arrow" :class="{ 'expanded': showActivities }">
						<text>›</text>
					</view>
				</view>
				<view class="activity-list" v-show="showActivities">
					<block v-if="recentActivities.length > 0">
						<view class="activity-wrapper" v-for="activity in recentActivities" :key="activity.id">
							<activity-item 
								:activity="activity"
								@tap="goToActivityDetail(activity)"
							/>
							<view class="divider"></view>
						</view>
					</block>
					<view class="empty-tip" v-else>暂无活动</view>
				</view>
			</view>

			<!-- 成员列表 -->
			<view class="team-members">
				<view class="section-header" @tap="toggleMembers">
					<view class="header-left">
						<text class="section-title">球队成员</text>
						<text class="count">({{teamMembers.length}})</text>
						<!-- <view class="member-preview" v-if="!showMembers">
							<view class="member-count">
								<text>{{teamMembers.length}}</text>
							</view>
						</view> -->
					</view>
					<view class="arrow" :class="{ 'expanded': showMembers }">
						<text>›</text>
					</view>
				</view>
				<view class="members-grid" v-if="showMembers">
					<view 
						class="member-item" 
						v-for="member in teamMembers" 
						:key="member.id"
					>
						<image 
							class="member-avatar" 
							:src="member.sysUser.avatar || '/static/avatars/default-avatar.jpg'" 
							mode="aspectFill"
							@tap.stop="goToUserProfile(member.sysUser.userId)"
						/>
						<text class="member-name">{{member.sysUser.nickName}}</text>
					</view>
				</view>
			</view>

			<!-- 球队动态 -->
			<view class="team-moments">
				<view class="section-header" @tap="toggleMoments">
					<view class="header-left">
						<text class="section-title">球队动态</text>
						<text class="count">({{teamInfo.moments ? teamInfo.moments.length : 0}})</text>
					</view>
					<view class="arrow" :class="{ 'expanded': showMoments }">
						<text>›</text>
					</view>
				</view>
				<scroll-view class="moments-list" scroll-x="true" v-show="showMoments">
					<view class="moment-item" v-for="(moment, index) in teamInfo.moments" :key="index"
						@tap="previewMedia(moment)">
						<image v-if="moment.type === 'image'" class="moment-media" :src="moment.url" mode="aspectFill">
						</image>
						<view v-if="moment.type === 'video'" class="moment-media video-container">
							<image class="moment-media" :src="moment.cover" mode="aspectFill"></image>
							<image class="play-icon" src="/static/icons/play.png"></image>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 底部位，防止内容被底部按钮遮挡 -->
			<view class="bottom-placeholder"></view>
		</scroll-view>

		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<view class="action-row">
				<!-- <button v-if="showJoinButton && teamInfo.joinType!=='invite'" class="action-btn primary"
					@tap="handleJoinTeam">
					<image src="/static/icons/join.png"></image>
					<text>申请加入</text>
				</button> -->
				<button class="action-btn primary" @tap="handleContactTeam">
					<image src="/static/icons/contact.png"></image>
					<text>联系球队</text>
				</button>
			</view>

			<view class="action-row">
				<button class="action-btn secondary" @tap="handleShare">
					<image src="/static/icons/share.png"></image>
					<text>分享名片</text>
				</button>
				<!-- <button class="action-btn secondary" @tap="generatePoster">
					<image src="/static/icons/poster.png"></image>
					<text>生成海报</text>
				</button> -->
				<button class="action-btn secondary" @tap="showQrCode">
					<image src="/static/icons/qrcode.png"></image>
					<text>小程序码</text>
				</button>
			</view>
		</view>

		<!-- 小程序码弹窗 -->
		<view class="qrcode-modal" v-if="showQrcodePopup">
			<view class="modal-mask" @tap="closeQrCode"></view>
			<view class="qrcode-popup">
				<image class="qrcode" :src="teamInfo.qrcode" mode="aspectFit"></image>
				<text class="popup-tip">保存小程序码</text>
				<button class="save-btn" @tap="saveQrCode">保存到相册</button>
				<text class="close-btn" @tap="closeQrCode">关闭</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getTeams
	} from '@/api/youqiu/team.js'
	import ActivityItem from '@/components/activity-item/index.vue'
	import { listMembers } from '@/api/youqiu/members'
	import { listActivity } from '@/api/youqiu/activity'

	export default {
		components: {
			ActivityItem
		},
		data() {
			return {
				teamId: '',
				teamInfo: {},
				teamTags: [],
				recentActivities: [],
				teamMembers: [],
				showQrcodePopup: false,
				showActivities: false,
				showMembers: false,
				showMoments: false,
				userInfo: null,
			}
		},
		computed: {
			showJoinButton() {
				if (!this.userInfo) return false
				
				const isMember = this.teamMembers.some(member => 
					member.sysUser.userId === this.userInfo.userId
				)
				//如果还不是球队成员 再看入队方式是否是只能邀请
				return !isMember
			}
		},
		onLoad(options) {
			if (options.teamId) {
				this.teamId = options.teamId
				this.getTeamInfo()
				this.getRecentActivities()
				this.getTeamMembers()
			}
			const storage_data = uni.getStorageSync('storage_data')
			if (storage_data && storage_data.vuex_user_info) {
				this.userInfo = storage_data.vuex_user_info
			}
		},
		methods: {
			getTeamInfo() {
				console.log('获取球队信息:', this.teamId)
				getTeams(this.teamId).then(res => {
					console.log(res)
					this.teamInfo = res.data
					if (this.teamInfo.tags) {
						this.teamTags = this.teamInfo.tags.split(',').map(tag => tag.trim()).filter(tag => tag)
					}
				})
			},
			// 预览媒体
			previewMedia(moment) {
				if (moment.type === 'image') {
					uni.previewImage({
						urls: [moment.url]
					})
				} else if (moment.type === 'video') {
					// 播放视频
					uni.navigateTo({
						url: `/pages/common/video-player?url=${encodeURIComponent(moment.url)}`
					})
				}
			},

			// 申请加入球队
			handleJoinTeam() {
				uni.navigateTo({
					url: `/pages/team/join/index?teamId=${this.teamId}`,
					fail: (err) => {
						console.error('跳转申请页面失败:', err)
						uni.showToast({
							title: '页面转失败',
							icon: 'none'
						})
					}
				})
			},

			// 联系球队
			handleContactTeam() {
				uni.showActionSheet({
					itemList: ['复制微信号', '拨打电话'],
					success: (res) => {
						if (res.tapIndex === 0) {
							uni.setClipboardData({
								data: 'yudg8888',
								success: () => {
									uni.showToast({
										title: '微信号已复制'
									})
								}
							})
						} else if (res.tapIndex === 1) {
							uni.makePhoneCall({
								phoneNumber: '19156076698'
							})
						}
					}
				})
			},

			// 分享名片
			handleShare() {
				uni.showShareMenu({
					withShareTicket: true,
					menus: ['shareAppMessage', 'shareTimeline']
				})
				// 提示用户点击右上角分享
				uni.showToast({
					title: '点击右上角分享',
					icon: 'none',
					duration: 2000
				})
			},

			// 生成海报
			generatePoster() {
				// TODO: 实现海报生成逻辑
				uni.showLoading({
					title: '生成中...'
				})
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '海报已保存',
						icon: 'success'
					})
				}, 1500)
			},

			// 显示小程序码
			showQrCode() {
				this.showQrcodePopup = true
			},

			// 关闭小程序码
			closeQrCode() {
				this.showQrcodePopup = false
			},

			// 保存小程序码
			saveQrCode() {
				uni.saveImageToPhotosAlbum({
					filePath: this.teamInfo.qrcode,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
						this.closeQrCode()
					}
				})
			},

			// 获取最近一周活动
			getRecentActivities() {
				const now = new Date()
				// 获取未来一周的活动
				const weekLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
				
				listActivity({
					teamId: this.teamId,
					startTime: now.toISOString().split('T')[0],
					endTime: weekLater.toISOString().split('T')[0],
					orderByColumn: 'activity_time',  // 按活动时间排序
					isAsc: 'asc'  // 升序排列
				}).then(res => {
					if (res.code === 200) {
						this.recentActivities = res.rows || []
					}
				})
			},

			// 获取球队成员
			getTeamMembers() {
				listMembers({
					teamId: this.teamId,
					pageSize: 1000,
					pageNum: 1
				}).then(res => {
					if (res.code === 200) {
						this.teamMembers = res.rows || []
					}
				})
			},

			// 跳转到用户详情页
			goToUserProfile(userId) {
				if (userId) {
					uni.navigateTo({
						url: `/pages/profile/detail?userId=${userId}`
					})
				} else {
					uni.showToast({
						title: '用户信息不存在',
						icon: 'none'
					})
				}
			},

			// 跳转到活动详情页
			goToActivityDetail(activity) {
				uni.navigateTo({
					url: `/pages/activity/detail?id=${activity.id}`
				})
			},

			toggleActivities() {
				this.showActivities = !this.showActivities
			},

			toggleMembers() {
				this.showMembers = !this.showMembers
			},

			toggleMoments() {
				this.showMoments = !this.showMoments
			},

			handleEdit() {
				uni.navigateTo({
					url: `/pages/team/edit?teamId=${this.teamId}`
				})
			},

			handleManageAction(index) {
				switch(index) {
					case 0: // 编辑球队
						this.handleEdit()
						break
					// ... 其他 case 保持不变 ...
				}
			}
		},
		// 定义分享行为
		onShareAppMessage() {
			const title = this.teamInfo.name ? `${this.teamInfo.name}的球队名片` : '球队名片'
			const path = `/pages/team/detail?teamId=${this.teamId}`
			const imageUrl = this.teamInfo.logo || '/static/images/share-default.jpg'

			return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: () => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					})
				},
				fail: () => {
					uni.showToast({
						title: '分享失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		min-height: 100vh;
		background: #f5f5f5;
		padding-bottom: env(safe-area-inset-bottom);

		.content-scroll {
			height: 100vh;
			padding: 20rpx 0;
		}

		.team-header {
			display: flex;
			align-items: center;
			background: #fff;
			padding: 30rpx 20rpx;
			margin-bottom: 20rpx;

			.team-logo {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 20rpx;
			}
		}

		.team-tags {
			padding: 20rpx 20rpx;
			background: #fff;
			margin-bottom: 20rpx;
			
			.tag {
				display: inline-block;
				padding: 6rpx 20rpx;
				background: #f5f5f5;
				border-radius: 24rpx;
				font-size: 24rpx;
				color: #666;
				margin-right: 16rpx;
				margin-bottom: 16rpx;
			}
		}

		.team-description {
			background: #fff;
			padding: 30rpx 20rpx;
			margin-bottom: 20rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}

			.description-content {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
			}
		}

		.team-stats {
			display: flex;
			justify-content: space-around;
			background: #fff;
			padding: 30rpx 20rpx;
			margin-bottom: 20rpx;
		}

		.recent-activities {
			background: #fff;
			margin-bottom: 20rpx;

			.section-header {
				padding: 20rpx;
			}

			.activity-list {
				.activity-wrapper {
					padding: 0 20rpx;
				}
			}
		}

		.team-members {
			background: #fff;
			margin-bottom: 20rpx;

			.section-header {
				padding: 20rpx;
			}

			.members-grid {
				display: grid;
				grid-template-columns: repeat(6, 1fr);
				gap: 20rpx;
				padding: 20rpx;

				.member-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					width: 100%;

					.member-avatar {
						width: 90rpx;
						height: 90rpx;
						border-radius: 50%;
						margin-bottom: 10rpx;
					}

					.member-name {
						font-size: 24rpx;
						color: #666;
						max-width: 100%;
						text-align: center;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						padding: 0 4rpx;
						box-sizing: border-box;
					}
				}
			}
		}

		.team-moments {
			background: #fff;
			margin-bottom: 20rpx;

			.section-header {
				padding: 20rpx;
			}

			.moments-list {
				white-space: nowrap;
				padding: 0 20rpx 20rpx;
			}
		}
	}

	.bottom-placeholder {
		height: 240rpx;
	}

	.team-info {
		flex: 1;
	}

	.team-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}

	.team-meta {
		font-size: 24rpx;
		color: #999;
	}

	.team-location {
		margin-right: 20rpx;
	}

	.team-tags {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.tag {
		padding: 8rpx 20rpx;
		background-color: #f0f9f0;
		color: #4CAF50;
		border-radius: 6rpx;
		font-size: 24rpx;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-left: 20rpx;
		border-left: 8rpx solid #4CAF50;
	}

	.team-description {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.description-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}

	.team-stats {
		display: flex;
		justify-content: space-around;
		padding: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 120rpx;
	}

	.stat-value {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		line-height: 56rpx;
		height: 56rpx;
		display: flex;
		align-items: center;
	}

	.stat-label {
		font-size: 28rpx;
		color: #666;
		line-height: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
	}

	.recent-activities {
		background: #fff;
		padding: 30rpx;
		margin-top: 20rpx;
		border-radius: 12rpx;
	}

	.team-members {
		background: #fff;
		padding: 30rpx;
		margin-top: 20rpx;
		border-radius: 12rpx;
	}

	.members-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.member-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: calc((100% - 80rpx) / 5);
	}

	.member-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.member-name {
		font-size: 24rpx;
		color: #333;
		text-align: center;
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.empty-tip {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.team-moments {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
	}

	.moments-list {
		white-space: nowrap;
		padding: 10rpx 0;
	}

	.moment-item {
		display: inline-block;
		width: 240rpx;
		height: 240rpx;
		margin-right: 20rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.moment-media {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.video-container {
		position: relative;
	}

	.play-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 60rpx;
		height: 60rpx;
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 1;
	}

	.action-row {
		display: flex;
		justify-content: space-around;
		margin-bottom: 20rpx;
	}

	.action-row:last-child {
		margin-bottom: 0;
	}

	.action-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		border: none;
	}

	.action-btn image {
		width: 36rpx;
		height: 36rpx;
		margin-right: 10rpx;
	}

	.action-btn.primary {
		background-color: #4CAF50;
		color: #fff;
		flex: 1;
		margin: 0 10rpx;
	}

	.action-btn.secondary {
		background-color: #f5f5f5;
		color: #666;
		flex: 1;
		margin: 0 10rpx;
	}

	.qrcode-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
	}

	.qrcode-popup {
		position: relative;
		background-color: #fff;
		padding: 40rpx;
		border-radius: 12rpx;
		width: 560rpx;
		z-index: 1000;
	}

	.qrcode {
		width: 400rpx;
		height: 400rpx;
		margin: 0 auto 20rpx;
	}

	.popup-tip {
		display: block;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 30rpx;
	}

	.save-btn {
		background-color: #4CAF50;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		margin: 0;
	}

	.close-btn {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 40rpx;
		color: #999;
		line-height: 1;
	}

	.recent-activities .activity-wrapper {
		position: relative;
	}
	
	.recent-activities .activity-wrapper:last-child .divider {
		display: none;
	}
	
	.recent-activities .divider {
		height: 1rpx;
		background-color: #eee;
		margin: 0 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		cursor: pointer;
		user-select: none;
	}

	.section-header:active {
		background-color: #f5f5f5;
	}

	.header-left {
		display: flex;
		align-items: center;
		
		.member-preview {
			margin-left: 20rpx;
			
			.member-count {
				width: 40rpx;
				height: 40rpx;
				background-color: #f5f5f5;
				border-radius: 6rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
	}

	.count {
		font-size: 28rpx;
		color: #999;
		margin-left: 8rpx;
	}

	.arrow {
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 32rpx;
		transform: rotate(90deg);
		transition: transform 0.3s ease;
	}

	.arrow.expanded {
		transform: rotate(-90deg);
	}

	.activity-list,
	.members-grid,
	.moments-list {
		transition: max-height 0.3s ease;
	}
</style>